<template>
    <button
        class="avatar-upload pa-0 ma-0  rounded"
        :style="styles"
        hover-class="none"
        open-type="chooseAvatar"
        @click="chooseAvatar"
        @chooseavatar="chooseAvatar"
    >
        <image style="width: 72rpx;height: 72rpx;" :src="modelValue" v-if="modelValue" />
        <slot v-else>
            <tm-button :margin="[0,0]" :round="15" :height="72" :width="72" icon="tmicon-plus"></tm-button>
        </slot>
    </button>
</template>
<script lang="ts" setup>
import { useAuthStore } from '@/state/modules/auth';
import { toast } from '@/tmui/tool/function/util'
import { getUploadUrl } from '@/utils/env';
import { isBoolean } from '@/utils/is';
import { HideLoading, Loading, Toast } from '@/utils/uniapi/prompt';
import { computed, CSSProperties, onUnmounted } from 'vue'

const props = defineProps({
    modelValue: {
        type: String
    },
    fileKey: {
        type: String,
        default: 'uri'
    },
    size: {
        type: [String, Number],
        default: 86
    },
    round: {
        type: [Boolean, String, Number],
        default: false
    },
    border: {
        type: Boolean,
        default: true
    }
})
const emit = defineEmits<{
    (event: 'update:modelValue', value: string): void
}>()
const auth = useAuthStore()
const styles = computed<CSSProperties>(() => {
    return {
        width: props.size,
        height: props.size,
        borderRadius: isBoolean(props.round) ? (props.round ? '50%' : '') : props.round
    }
})

const chooseAvatar = (e: any) => {
    // #ifdef MP-WEIXIN
    const path = e.detail?.avatarUrl
    
    if (path) {
        uploadImageIng(path)
    }
    // #endif
}

const uploadImageIng = async (file: string) => {
    Loading('正在上传中...')
    
    try {
        const res: any = await uploadImage(file, auth.getToken)
        console.log(res);
        HideLoading()
        emit('update:modelValue', res[props.fileKey])
    } catch (error) {
        HideLoading()
        Toast(error.errMsg)
    }
}

function uploadImage(file:any, token?:string) {
    return new Promise((res, fail) => {
        uni.uploadFile({
            url: getUploadUrl() + '/image',
            filePath: file,
            header: {
                token,
            },
             name: 'file',
            fileType: 'image',
            success(result) {
                console.log(result);
                if(result.statusCode!= 200) {
                    return fail({code: 0, errMsg: '上传失败'})
                }
                const  {code, msg, data} = JSON.parse(result.data)
                if(code!= 1) {
                    return toast(msg)
                }
                res(data)
            },
            fail(err) {
                console.log(err);
                fail(err)
            }
        })
    })
}
onUnmounted(() => {
    uni.$off('uAvatarCropper')
})
</script>

<style lang="scss" scoped>
.avatar-upload {
    background: #fff;
    overflow: hidden;
    &::after {
        border: none;
    }
}
</style>
